const Koa = require('koa');
const cors = require('koa-cors');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const axios = require('axios');
const allowedMethods = require('allowed-methods')
const app = new Koa();
const router = new Router();
// 定义一个POST路由
router.post("/take", async (ctx) => {
    // 当这个路由被访问时，它会从请求体（ctx.request.body）中获取query字段。
    const { query } = ctx.request.body;
    if (!query) {
        ctx.status = 400;
        ctx.body = "query is required";
        return;
    }
    // 如果query字段存在，服务器会使用axios发送一个POST请求到https://qianfan.baidubce.com/v2/app/conversation/runs
    const options = {
        method: 'POST',
        url: 'https://qianfan.baidubce.com/v2/app/conversation/runs',
        headers: {
            'Content-Type': 'application/json',
            'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-Tlzuk90zwCDZ1Hm9Uo334/2a737d12c6ca041007ca32be1386d51954c22aa4'
        },
        data: JSON.stringify({
            "app_id": "8e74d5c7-a315-4cf3-ac3a-421ffd1086e3",
            "query": query,
            "conversation_id": "34a70ad3-a2ae-45b1-a9b7-6c09bea30cee",
            "stream": false
        })
    };
   
    try {
        const res = await axios(options);
        ctx.body = res.data;//返回给原始请求者。
    }
    catch (err) {
        ctx.status = 500;
        ctx.body = err.message;//服务器会返回500状态码和错误信息
    }
})
app.use(bodyParser());
// 使用router.routes()和allowedMethods()中间件处理路由和不支持的请求方法
app.use(cors()).use(router.routes()).use(allowedMethods());
app.listen(9999, () => {
    console.log("9999启动成功");
})